package org.example.utils;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import static org.example.config.Constant.WX_ACCESS_TOKEN_URL;

@Service
public class WxAccessTokenClient {

    @Value("${wxAppId: }")
    private String appId;
    @Value("${wxAppSecret: }")
    private String appSecret;

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    private static class AccessToken {
        String token;
        long expireTime = 0;

        public boolean isExpire() {
            return System.currentTimeMillis() > expireTime;
        }
    }

    private volatile AccessToken accessToken = new AccessToken();

    public String getAccessToken() {
        if (accessToken.isExpire()) {
            synchronized (this) {
                if (accessToken.isExpire()) {
                    //https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
                    HashMap map = new HashMap();
                    map.put("grant_type", "client_credential");
                    map.put("appid", appId);
                    map.put("secret", appSecret);
                    HttpResult<Map> httpResult = HttpUtils.get(WX_ACCESS_TOKEN_URL, null, map, Map.class, null);
                    String accessTokenNew = (String) httpResult.getResult().get("access_token");
                    Integer expires_in = (Integer) httpResult.getResult().get("expires_in");
                    long nextExpireTime = expires_in * 1000 + System.currentTimeMillis();
                    accessToken = AccessToken.builder().token(accessTokenNew).expireTime(nextExpireTime).build();
                }
            }
        }
        return accessToken.getToken();
    }
}
